package bc.swim2.ejb.session;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import bc.swim2.ejb.entity.Ability;
import bc.swim2.ejb.entity.RegisteredUser;

/**
 * Session Bean implementation class AbilityManagerBean
 */
@Stateless
public class AbilityManagerBean implements AbilityManagerBeanRemote {

	/**
	 * Default constructor.
	 */
	public AbilityManagerBean() {
	}

	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;


	@SuppressWarnings("unchecked")
	public List<Ability> getAbilityList() {

		List<Ability> abilities = null;

		try {
			Query q = em.createNamedQuery("Ability.getAbilityList");
			abilities =  q.getResultList();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		return abilities;
	}

	@Override
	public Ability insertAbility(String name) {
		try {
			Ability newAbility = new Ability();
			newAbility.setName(name);
			em.persist(newAbility);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void removeAbility(int abilityId) {
		
		Query q = em.createNamedQuery("Ability.getAbilityById");
		q.setParameter("id", abilityId);
		List<Ability> al;
		al = q.getResultList();
		em.remove(al.get(0));
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean existsAbilityWithName(String newAbility) {
		
		boolean itExists = false;
		
		Query q = em.createNamedQuery("Ability.getAbilityByName");
		q.setParameter("name", newAbility);
		List<Ability> al;
		al = q.getResultList();
		
		if(!(al.isEmpty())){
			itExists = true;
		} 
		
		return itExists;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Ability> getUserAbility(RegisteredUser user) {
		List<Ability> abilities = null;
		int userId = user.getId();
		
		try{
			Query q = em.createNamedQuery("Ability.getAbilityByUserId");
			q.setParameter("id", userId);
			abilities = q.getResultList();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return abilities;
	}

	@Override
	public Ability getAbilityById(int abilityId) {
		
		Ability a = null;
		
		try {
			Query q = em.createNamedQuery("Ability.getAbilityById");
			q.setParameter("id", abilityId);
			
			a = (Ability) q.getResultList().get(0);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return a;
	}

}
